package com.zhengxiang.onlinexamination.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class WxUtils {

    public final static String API_KEY = "wxe708705247441d41";
    public final static String SECRET_KEY="fd519a35bfe81221b6beacbc84dcd704";

    /**
     * 生成带参小程序二维码
     *
     * @param parameter    参数
     * @param accessToken token
     */
    public static InputStream getWxQr(String parameter, String accessToken, String page) {
        String requestUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        // 发送请求参数
        JSONObject paramJson = new JSONObject();
        paramJson.put("scene",new String(parameter.getBytes(), Charset.forName("UTF-8")));
        paramJson.put("page", page);
        paramJson.put("width", 430);
        paramJson.put("auto_color", true);
        paramJson.put("check_path", false);
        //开发版
		paramJson.put("env_version","develop");
        //体验版
//		paramJson.put("env_version","trial");
        //正式版
//        paramJson.put("env_version","release");
        HttpResponse execute = null;
        try {
            execute = HttpRequest.post(requestUrl).body(paramJson.toJSONString()).execute();
            return execute.bodyStream();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 用于获取access_token
     *
     */
    public static String getWxToken() {

        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + API_KEY
                + "&secret=" + SECRET_KEY;

        String body = HttpRequest.post(requestUrl).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(body);
        String accesstoken = jsonObject.getString("access_token");
        return accesstoken;
    }

    public static void main(String[] args) throws IOException {
        //生成二维码地址,扫码入场考试
        StringBuffer params = new StringBuffer();
        params.append("d=").append(1);
        InputStream wxQr = WxUtils.getWxQr(params.toString(), WxUtils.getWxToken(), "pages/syudy/answerQuestion/index");
        BufferedImage image = ImageIO.read(wxQr);
//        BufferedImage outImage = QRCodeUtil.addBottomText(image, new String("测定".getBytes(), "UTF-8"));
        ImageIO.write(image, "png", new File("C:\\Users\\Mayn\\Pictures\\www.png"));

    }
}
